package main

import (
	"context"
	"embed"
	"gopin/apis"
	"gopin/config"
	"gopin/logger"
	"time"

	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

//go:embed all:frontend/dist
var assets embed.FS

func main() {
	logPath, err := logger.InitLogger()
	if err != nil {
		println("初始化日志失败:", err.Error())
		return
	}
	defer logger.Sync()

	// 打印日志文件路径
	println("日志文件路径:", logPath)

	// 获取配置实例
	cfg := config.GetInstance()
	width, height := cfg.GetWindowSize()

	// 记录窗口信息
	logger.Info("窗口初始化",
		"width", width,
		"height", height,
	)

	// Create an instance of the app structure
	proxy := NewProxy()
	apis := apis.NewApis()
	// Create application with options
	err = wails.Run(&options.App{
		Title:     "gopin",
		Width:     width,
		Height:    height,
		MinWidth:  800,
		MinHeight: 600,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
		OnStartup: func(ctx context.Context) {
			x, y := cfg.GetWindowPosition()
			runtime.WindowSetPosition(ctx, x, y)

			go func() {
				for {
					newX, newY := runtime.WindowGetPosition(ctx)
					if newX != x || newY != y {
						cfg.SetWindowPosition(newX, newY)
						x, y = newX, newY
					}
					newWidth, newHeight := runtime.WindowGetSize(ctx)
					if newWidth != width || newHeight != height {
						cfg.SetWindowSize(newWidth, newHeight)
						width, height = newWidth, newHeight
					}
					time.Sleep(2 * time.Second)
				}
			}()

			proxy.Startup(ctx)
		},
		OnShutdown: func(ctx context.Context) {
			logger.Info("应用关闭")
			proxy.Shutdown(ctx)
		},
		Bind: []interface{}{
			proxy,
			apis,
		},
	})

	if err != nil {
		logger.Error("应用启动失败",
			"error", err,
		)
		println("Error:", err.Error())
	}
}
